﻿<template>
  <div class="material-withdrawal">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-icon">📦</div>
      <h1 class="page-title">物资领用</h1>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="领用人:">
          <el-input
            v-model="searchForm.recipient"
            placeholder="请输入领用人"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="领用日期:">
          <el-date-picker
            v-model="searchForm.withdrawalDate"
            type="date"
            placeholder="请选择领用日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="审批状态:">
          <el-select
            v-model="searchForm.approvalStatus"
            placeholder="全部"
            clearable
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="待审批" value="0" />
            <el-option label="审批中" value="1" />
            <el-option label="已通过" value="2" />
            <el-option label="已驳回" value="3" />
            <el-option label="已撤回" value="4" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="审批人:">
          <el-input
            v-model="searchForm.approvalByName"
            placeholder="请输入审批人"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            查询
          </el-button>
          <el-button @click="handleReset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <el-button type="primary" @click="handleAdd" :icon="Plus">
        新增
      </el-button>
      <el-button type="danger" @click="handleBatchDelete" :icon="Delete" :disabled="!hasSelected">
        删除
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="title" label="标题" min-width="150">
          <template #default="{ row }">
            <span class="title-text">{{ row.title }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="usageDescription" label="用途描述" min-width="200">
          <template #default="{ row }">
            <span class="description-text">{{ row.usageDescription }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="recipient" label="领用人" width="120" />
        
        <el-table-column prop="withdrawalDate" label="领用日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.withdrawalDate) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="note" label="备注" width="100">
          <template #default="{ row }">
            {{ row.note || '-' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="createdTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="goodName" label="货物名称" width="120">
          <template #default="{ row }">
            {{ row.goodName || '-' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="withdrawalQuantity" label="领用数量" width="100">
          <template #default="{ row }">
            {{ row.withdrawalQuantity || 0 }}
          </template>
        </el-table-column>
        
        <el-table-column prop="approvalStatus" label="审批状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.approvalStatus)">
              {{ getStatusText(row.approvalStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="approvalByName" label="审批人" width="120">
          <template #default="{ row }">
            {{ row.approvalByName || '-' }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <!-- 已撤回状态 -->
              <template v-if="row.approvalStatus === 4">
                <el-button link type="primary" @click="handleEdit(row)" :icon="Edit">
                  编辑
                </el-button>
                <el-button link type="danger" @click="handleDelete(row)" :icon="Delete">
                  删除
                </el-button>
                <el-button link type="success" @click="handleView(row)" :icon="View">
                  查看
                </el-button>
                <el-button link type="warning" @click="handleSubmitApproval(row)" :icon="Check">
                  提交审批
                </el-button>
              </template>
              
              <!-- 已驳回状态 -->
              <template v-else-if="row.approvalStatus === 3">
                <el-button link type="primary" @click="handleEdit(row)" :icon="Edit">
                  编辑
                </el-button>
                <el-button link type="danger" @click="handleDelete(row)" :icon="Delete">
                  删除
                </el-button>
                <el-button link type="success" @click="handleView(row)" :icon="View">
                  查看
                </el-button>
                <el-button link type="warning" @click="handleSubmitApproval(row)" :icon="Check">
                  提交审批
                </el-button>
              </template>
              
              <!-- 待审批状态 -->
              <template v-else-if="row.approvalStatus === 0">
                <el-button link type="primary" @click="handleEdit(row)" :icon="Edit">
                  编辑
                </el-button>
                <el-button link type="danger" @click="handleDelete(row)" :icon="Delete">
                  删除
                </el-button>
                <el-button link type="success" @click="handleView(row)" :icon="View">
                  查看
                </el-button>
                <el-button link type="warning" @click="handleSubmitApproval(row)" :icon="Check">
                  提交审批
                </el-button>
              </template>
              
              <!-- 审批中状态 -->
              <template v-else-if="row.approvalStatus === 1">
                <el-button link type="primary" @click="handleEdit(row)" :icon="Edit">
                  编辑
                </el-button>
                <el-button link type="danger" @click="handleDelete(row)" :icon="Delete">
                  删除
                </el-button>
                <el-button link type="success" @click="handleView(row)" :icon="View">
                  查看
                </el-button>
                <el-button link type="info" @click="handleCancelApproval(row)" :icon="Close">
                  撤回审批
                </el-button>
              </template>
              
              <!-- 已通过状态 -->
              <template v-else-if="row.approvalStatus === 2">
                <el-button link type="primary" @click="handleEdit(row)" :icon="Edit">
                  编辑
                </el-button>
                <el-button link type="danger" @click="handleDelete(row)" :icon="Delete">
                  删除
                </el-button>
                <el-button link type="success" @click="handleView(row)" :icon="View">
                  查看
                </el-button>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Delete, 
  Edit, 
  View, 
  Check,
  Close
} from '@element-plus/icons-vue'
import { materialApi } from '@/api'

// 路由
const router = useRouter()

// 加载状态
const loading = ref(false)

// 搜索表单 - 根据API接口调整字段名
const searchForm = reactive({
  recipient: '',
  withdrawalDate: '',
  approvalStatus: '',
  approvalByName: ''  // 修改为API接口字段名
})

// 表格数据
const tableData = ref([])

// 选中的行
const selectedRows = ref([])

// 分页信息 - 根据API接口调整字段名
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 是否有选中项
const hasSelected = computed(() => selectedRows.value.length > 0)

// 获取状态类型 - 根据API接口调整状态值
const getStatusType = (status) => {
  const statusMap = {
    0: 'warning',  // 待审批
    1: 'info',     // 审批中
    2: 'success',  // 已通过
    3: 'danger',   // 已驳回
    4: 'info'      // 已撤回
  }
  return statusMap[status] || 'info'
}

// 获取状态文本 - 根据API接口调整状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待审批',
    1: '审批中',
    2: '已通过',
    3: '已驳回',
    4: '已撤回'
  }
  return statusMap[status] || '未知'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取表格数据 - 使用正确的API接口
const fetchTableData = async () => {
  try {
    loading.value = true
    
    // 根据API接口构建请求参数
    const params = {
      PageIndex: pagination.currentPage,  // API接口字段名
      PageSize: pagination.pageSize,     // API接口字段名
      Recipient: searchForm.recipient,   // API接口字段名
      WithdrawalDate: searchForm.withdrawalDate,  // API接口字段名
      ApprovalStatus: searchForm.approvalStatus,  // API接口字段名
      ApprovalByName: searchForm.approvalByName   // API接口字段名
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    console.log('请求参数:', params)
    
    // 使用封装的API方法
    const response = await materialApi.getPagedMaterialWithdrawal(params)
    
    console.log('API响应:', response)
    
    if (response.code === 200) {
      // 根据API响应结构调整数据映射
      const data = response.data
      console.log('API响应数据结构:', data)
      
      // 安全检查数据结构
      if (data && Array.isArray(data.data)) {
        tableData.value = data.data
        pagination.total = data.totalCount || 0
      } else if (Array.isArray(data)) {
        // 如果data直接是数组
        tableData.value = data
        pagination.total = data.length
      } else {
        console.warn('意外的数据结构:', data)
        tableData.value = []
        pagination.total = 0
      }
      
      console.log('获取数据成功:', tableData.value)
    } else {
      throw new Error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    // 使用模拟数据
    tableData.value = [
      {
        id: 1,
        title: '日常汽车维护',
        usageDescription: '汽车爆胎,需要更换',
        recipient: '王小宝',
        withdrawalDate: '2020-09-07T00:00:00',
        note: '',
        createdTime: '2020-10-07T13:00:00',
        goodName: '轮胎',
        withdrawalQuantity: 2,
        processDetailCode: 'MW001',
        approvalStatus: 0,
        approvalByName: null,
        approvalTypeCode: 'T005'
      },
      {
        id: 2,
        title: '办公用品领用',
        usageDescription: '打印机耗材更换',
        recipient: '李小明',
        withdrawalDate: '2020-09-08T00:00:00',
        note: '紧急需求',
        createdTime: '2020-10-08T09:30:00',
        goodName: '打印机',
        withdrawalQuantity: 1,
        processDetailCode: 'MW002',
        approvalStatus: 2,
        approvalByName: '张经理',
        approvalTypeCode: 'T005'
      },
      {
        id: 3,
        title: '维修工具领用',
        usageDescription: '设备维修专用工具',
        recipient: '赵师傅',
        withdrawalDate: '2020-09-09T00:00:00',
        note: '',
        createdTime: '2020-10-09T14:20:00',
        goodName: '扳手',
        withdrawalQuantity: 5,
        processDetailCode: 'MW003',
        approvalStatus: 3,
        approvalByName: '王主管',
        approvalTypeCode: 'T005'
      }
    ]
    pagination.total = 100
    ElMessage.warning('使用模拟数据')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchTableData()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.currentPage = 1
  fetchTableData()
}

// 新增
const handleAdd = () => {
  router.push('/AddMaterialWithdrawal')
}

// 编辑 - 调用API接口获取详情
const handleEdit = async (row) => {
  // 检查是否可以编辑
  if (row.approvalStatus === 2) {
    ElMessage.warning('已通过的记录无法编辑')
    return
  }
  
  try {
    // 显示加载提示
    const loadingMessage = ElMessage({
      message: '正在加载详情数据...',
      type: 'info',
      duration: 0,
      showClose: false
    })
    
    try {
      // 调用封装的API方法获取详情数据
      const response = await materialApi.getMaterialWithdrawalDetail(row.id)
      
      console.log('编辑-获取详情API响应:', response)
      
      // 关闭加载提示
      loadingMessage.close()
      
      if (response.code === 200) {
        // API调用成功，跳转到编辑页面并传递详情数据
        router.push({
          path: '/AddMaterialWithdrawal',
          query: { 
            id: row.id, 
            mode: 'edit'
          }
        })
        
        ElMessage.success('详情数据加载成功')
      } else {
        throw new Error(response.message || '获取详情失败')
      }
    } catch (apiError) {
      // 关闭加载提示
      loadingMessage.close()
      throw apiError
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    if (error.response?.data?.message) {
      ElMessage.error(`获取详情失败：${error.response.data.message}`)
    } else {
      ElMessage.error('获取详情失败，请重试')
    }
  }
}

// 查看 - 调用API接口获取详情（只读模式）
const handleView = async (row) => {
  try {
    // 显示加载提示
    const loadingMessage = ElMessage({
      message: '正在加载详情数据...',
      type: 'info',
      duration: 0,
      showClose: false
    })
    
    try {
      // 调用封装的API方法获取详情数据
      const response = await materialApi.getMaterialWithdrawalDetail(row.id)
      
      console.log('查看详情API响应:', response)
      
      // 关闭加载提示
      loadingMessage.close()
      
      if (response.code === 200) {
        // 获取API返回的详情数据
        const detailData = response.data
        
        // 将详情数据存储到sessionStorage中，供查看页面使用
        sessionStorage.setItem('materialWithdrawalDetail', JSON.stringify(detailData))
        
        // API调用成功，跳转到查看页面（只读模式）
        router.push({
          path: '/AddMaterialWithdrawal',
          query: { 
            id: row.id, 
            mode: 'view',
            readonly: 'true'  // 明确标识为只读模式
          }
        })
        
        ElMessage.success('详情数据加载成功')
      } else {
        throw new Error(response.message || '获取详情失败')
      }
    } catch (apiError) {
      // 关闭加载提示
      loadingMessage.close()
      throw apiError
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    if (error.response?.data?.message) {
      ElMessage.error(`获取详情失败：${error.response.data.message}`)
    } else {
      ElMessage.error('获取详情失败，请重试')
    }
  }
}

// 删除 - 简化提示
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除"${row.title}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    console.log('删除记录ID:', row.id)
    
    // 显示删除进度提示
    const loadingMessage = ElMessage({
      message: '正在删除记录，请稍候...',
      type: 'info',
      duration: 0,
      showClose: false
    })
    
    try {
      // 调用封装的API方法删除记录
      const response = await materialApi.deleteMaterialWithdrawal(row.id)
      
      console.log('删除API响应:', response)
      
      // 关闭加载提示
      loadingMessage.close()
      
      if (response.code === 200) {
        ElMessage.success('删除成功')
        fetchTableData()
      } else {
        throw new Error(response.message || '删除失败')
      }
    } catch (apiError) {
      // 关闭加载提示
      loadingMessage.close()
      throw apiError
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      if (error.response?.data?.message) {
        ElMessage.error(`删除失败：${error.response.data.message}`)
      } else {
        ElMessage.error('删除失败，请重试')
      }
    }
  }
}

// 批量删除 - 根据API接口调整
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  
  try {
    // 简化的批量删除确认信息
    const confirmMessage = `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`
    
    await ElMessageBox.confirm(
      confirmMessage,
      '批量删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedRows.value.map(row => row.id)
    console.log('批量删除IDs:', ids)
    
    // 显示批量删除进度提示
    const loadingMessage = ElMessage({
      message: `正在删除 ${ids.length} 条记录，请稍候...`,
      type: 'info',
      duration: 0,
      showClose: false
    })
    
    try {
      // 调用封装的API方法批量删除记录
      const response = await materialApi.deleteListMaterialWithdrawal(ids)
      
      console.log('批量删除API响应:', response)
      
      // 关闭加载提示
      loadingMessage.close()
      
      if (response.code === 200) {
        ElMessage.success(`批量删除成功，共删除 ${response.data} 条记录`)
        selectedRows.value = []
        fetchTableData()
      } else {
        throw new Error(response.message || '批量删除失败')
      }
    } catch (apiError) {
      // 关闭加载提示
      loadingMessage.close()
      throw apiError
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      if (error.response?.data?.message) {
        ElMessage.error(`批量删除失败：${error.response.data.message}`)
      } else {
        ElMessage.error('批量删除失败，请重试')
      }
    }
  }
}

// 提交审批 - 新增功能
const handleSubmitApproval = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要提交"${row.title}"审批吗？`,
      '提交审批确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // 调用封装的API方法提交审批
    const response = await materialApi.submitMaterialWithdrawalApproval(row.id)
    
    if (response.code === 200) {
      ElMessage.success('提交审批成功')
      fetchTableData()
    } else {
      throw new Error(response.message || '提交审批失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交审批失败:', error)
      ElMessage.error('提交审批失败，请重试')
    }
  }
}

// 撤回审批 - 新增功能
const handleCancelApproval = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要撤回"${row.title}"审批吗？`,
      '撤回审批确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用封装的API方法撤回审批
    const response = await materialApi.cancelMaterialWithdrawalApproval(row.id)
    
    if (response.code === 200) {
      ElMessage.success('撤回审批成功')
      fetchTableData()
    } else {
      throw new Error(response.message || '撤回审批失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('撤回审批失败:', error)
      ElMessage.error('撤回审批失败，请重试')
    }
  }
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchTableData()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchTableData()
}

// 页面加载时获取数据
onMounted(() => {
  fetchTableData()
})
</script>

<style scoped>
.material-withdrawal {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-icon {
  font-size: 24px;
  margin-right: 12px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 20px;
}

.action-section {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.action-section .el-button {
  margin-right: 10px;
}

.table-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.title-text {
  font-weight: 500;
  color: #333;
}

.description-text {
  color: #666;
  line-height: 1.4;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.action-buttons .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

.pagination-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .material-withdrawal {
    padding: 10px;
  }
  
  .search-form {
    display: flex;
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    margin-bottom: 5px;
  }
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  font-weight: 600;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 分页样式 */
:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-pagination .el-pager li.is-active) {
  background-color: #409eff;
  color: white;
}

/* 删除确认对话框样式 - 简化 */
:deep(.delete-confirm-dialog) {
  width: 400px;
}

:deep(.delete-confirm-dialog .el-message-box__content) {
  padding: 15px;
}

:deep(.batch-delete-confirm-dialog) {
  width: 400px;
}

:deep(.batch-delete-confirm-dialog .el-message-box__content) {
  padding: 15px;
}

/* 消息提示样式优化 */
:deep(.el-message) {
  font-size: 14px;
}

:deep(.el-message--success) {
  background-color: #f0f9ff;
  border-color: #67c23a;
}

:deep(.el-message--error) {
  background-color: #fef0f0;
  border-color: #f56c6c;
}

:deep(.el-message--warning) {
  background-color: #fdf6ec;
  border-color: #e6a23c;
}

:deep(.el-message--info) {
  background-color: #f4f4f5;
  border-color: #909399;
}
</style>




